﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.IO;
using System.Xml;
using System.Windows.Media.Imaging;
using System.Windows.Pivot;

namespace SLPivotViewer
{
    public partial class MainPage : UserControl
    {
        BitmapImage bmp;
        pivotLoading _pvLoading;
        public MainPage()
        {
            InitializeComponent();
        }
        private void PivotViewer_Loaded(object sender, RoutedEventArgs e)
        {
            App app = (App)App.Current;
            CustomizedPivotViewer(app);
            if (!string.IsNullOrWhiteSpace(app.CXMLUrl))
            {
                LoadPivotViewerCollection(app.CXMLUrl);
            }
            
        }

        private void CustomizedPivotViewer(App app)
        {
            _pvLoading = new pivotLoading();
            PivotViewer.FilterBackground = CreateBrushFromString(app.URLFilter, app.ARGBFilter, app.StretchFilter);
            PivotViewer.InfoBackground = CreateBrushFromString(app.URLInfo, app.ARGBInfo, app.StretchInfo);
            PivotViewer.ContentBackground = CreateBrushFromString(app.URLContent, app.ARGBContent, app.StretchContent);
            PivotViewer.TitleBarBackground = CreateBrushFromString(app.URLTitle, app.ARGBTitle, app.StretchTitle);
            downloadDelegate = new CustomActionDelegate(CreateDownloadCustomAction);
            PivotViewer.RegisterCustomActionDelegate(downloadDelegate);
            PivotViewer.ItemActionExecuted += new EventHandler<System.Windows.Pivot.ItemActionEventArgs>(PivotViewer_ItemActionExecuted);
            
            PivotViewer.InfoVisibility=app.VisibilityInfo;
            PivotViewer.TitleBarVisibility=app.VisibilityTitle;
            PivotViewer.FilterVisibility=app.VisibilityFilter;


        }
        private CustomActionDelegate downloadDelegate;

        List<CustomAction> CreateDownloadCustomAction(string itemId)
        {
            List<CustomAction> ret = new List<CustomAction>();

            PivotItem item = PivotViewer.GetItem(itemId);

            ret.Add(new CustomAction("Download", new Uri("/SLPivotViewer;component/Assets/download.png", UriKind.Relative), item.Name, "Download"));
            ret.Add(new CustomAction("Go to item", new Uri("/SLPivotViewer;component/Assets/download.png", UriKind.Relative), item.Name, "GoTo"));

            return ret;
        }
        void PivotViewer_ItemActionExecuted(object sender, System.Windows.Pivot.ItemActionEventArgs e)
        {
            PivotItem item = PivotViewer.GetItem(e.ItemId);
            if (e.CustomActionId == "Download")
            {
                NavigateTo(new Uri(item.Href, UriKind.Absolute));
            }
            if (e.CustomActionId == "GoTo")
            {
                string strUrl = "";
                if (item.Facets.Keys.Contains("Item DispPage"))
                    strUrl = item.Facets["Item DispPage"][0].ToString();
                else
                    strUrl = item.Href;
                NavigateTo(new Uri(strUrl,UriKind.Absolute));
            }
            
        }
        

        private Brush CreateBrushFromString(string url, string argb, string stretch)
        {
            if (!string.IsNullOrEmpty(url))
            {
                ImageBrush brush = new ImageBrush();
                bmp = new BitmapImage(new Uri(url, UriKind.Absolute));
                brush.ImageSource = bmp;
                brush.Stretch = GetStretchFromString(stretch);

                return brush;
            }
            else if (!string.IsNullOrEmpty(argb))
            {
                string[] strArgb= argb.Split('|');
                Color col=Color.FromArgb(byte.Parse(strArgb[0]), byte.Parse(strArgb[1]), byte.Parse(strArgb[2]), byte.Parse(strArgb[3]));
                return new SolidColorBrush(col);
            }
            return null;
        }

        private Stretch GetStretchFromString(string stretch)
        {
            switch (stretch)
            {
                case "Fill":
                    return Stretch.Fill;
                case "None":
                    return Stretch.None;
                case "Uniform":
                    return Stretch.Uniform;
                case "Uniform to fill":
                    return Stretch.UniformToFill;
                default:
                    return Stretch.None;
            
            }
        }

        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {

            App app = (App)App.Current;
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
            this.Dispatcher.BeginInvoke(delegate()
            {
                string postData = "Facets=" + app.Facets;
                postData += "&ImageField=" + app.ImageField;
                postData += "&ImageSubstitue=" + app.ImageSubstitue;
                postData += "&FieldUrl=" + app.FieldUrl;
                postData += "&Infos=" + app.Infos;
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
                postStream.Write(byteArray, 0, postData.Length);
                postStream.Close();
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            });
        }
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {

            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            string responseString = streamRead.ReadToEnd();
            this.Dispatcher.BeginInvoke(delegate()
            {
                App app = (App)App.Current;
                string strKey = "";
                XmlReader reader = XmlReader.Create(new StringReader(responseString));
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.Name == "key")
                    {

                        strKey = reader.ReadInnerXml();
                    }
                }
                string strUrlQuery = request.RequestUri.AbsoluteUri;
                if (!string.IsNullOrEmpty(request.RequestUri.Query))
                {
                    strUrlQuery = request.RequestUri.AbsoluteUri.Replace(request.RequestUri.Query, "");
                }
                string ColUrl = strUrlQuery + "?key=" + strKey;
                PivotViewer.LoadCollection(ColUrl, string.Empty);
                //CustomizedPivotViewer(app);
            });
            streamResponse.Close();
            streamRead.Close();
            response.Close();
        }
        private void PivotViewer_LinkClicked(object sender, System.Windows.Pivot.LinkEventArgs e)
        {
            
            NavigateTo(e.Link);
        }

        private void PivotViewer_ItemDoubleClicked(object sender, System.Windows.Pivot.ItemEventArgs e)
        {
        }

        private void NavigateTo(Uri targetUrl)
        {
            if (targetUrl.LocalPath.EndsWith(".cxml", StringComparison.InvariantCultureIgnoreCase))
            {
                App app = (App)App.Current;
                if (app.CXMLUrl.Contains("AllWebNavigationCollection.cxml"))
                {
                    btnReset.Visibility = Visibility.Visible;
                    LayoutRoot.RowDefinitions[0].Height = new GridLength(20);
                }
                LoadPivotViewerCollection(targetUrl.AbsoluteUri);
            }
            else
            {
                App app = (App)App.Current;
                if (string.IsNullOrEmpty(app.ItemOpen) || app.ItemOpen == "1")
                    HtmlPage.Window.Navigate(targetUrl, "_blank");
                if (!string.IsNullOrEmpty(app.ItemOpen) && app.ItemOpen == "2")
                    HtmlPage.Window.Navigate(targetUrl);
            }
        }

        private void LoadPivotViewerCollection(string strColUrl)
        {
            string colUrl = HttpUtility.UrlDecode(strColUrl);
            HttpWebRequest myRequest =
                 (HttpWebRequest)HttpWebRequest.Create(colUrl);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            App app = (App)App.Current;
            if (!string.IsNullOrWhiteSpace(app.CXMLUrl))
            {
                LoadPivotViewerCollection(app.CXMLUrl);

            }
            btnReset.Visibility = Visibility.Collapsed;
            LayoutRoot.RowDefinitions[0].Height =new GridLength(0);

        }
        
    }
}
